<?php

namespace app\common\model;

use Overtrue\Pinyin\Pinyin;
use think\Model;

class WscateModel extends Model
{
    protected $pk = 'wscate_id'; //主键

    // 模型事件
    protected static function init()
    {
        // 新增前
        self::beforeInsert(function ($value) {
            // 分类名称
            if (!isset($value['wscate_name']) || $value['wscate_name'] == '') {
                return $value;
            }

            $value['wscate_title'] = $value['wscate_name'];
            $value['wscate_sort'] = 1000000;

            $pinyin = new Pinyin();
            $page = strtolower($pinyin->permalink($value['wscate_name']));
            $page = trim(substr($page, 0, 50), '-, ');
            $value['wscate_page'] = $page;
            return $value;
        });

        // 新增后
        self::afterInsert(function ($value) {

            $siteid = $value['wscate_siteid'];
            $columnid = $value['wscate_columnid'];

            // 更新排序
            $model = new WscateModel;
            $model->update_sort($siteid, $columnid);

            // 删除缓存
            self::delete_cache($siteid, $columnid);
        });

        // 更新前
        self::beforeUpdate(function ($value) {

            // 分类名称
            if (!isset($value['wscate_name']) || $value['wscate_name'] == '') {
                return $value;
            }

            if (isset($value['wscate_title']) && $value['wscate_title'] == '') {
                $value['wscate_title'] = $value['wscate_name'];
            }

            if (!isset($value['wscate_page']) || $value['wscate_page'] != '') {
                return $value;
            }

            $pinyin = new Pinyin();
            $page = strtolower($pinyin->permalink($value['wscate_name']));
            $page = trim(substr($page, 0, 50), '-, ');
            $value['wscate_page'] = $page;
            return $value;
        });

        // 更新后
        self::afterUpdate(function ($value) {
            if (!isset($value['wscate_siteid']) && !isset($value['wscate_columnid'])) {
                return $value;
            }
            // 删除缓存
            self::delete_cache($value['wscate_siteid'], $value['wscate_columnid']);
        });

        // 删除前
        self::beforeDelete(function ($value) {
            // 判断分类下是否有子类
            $id = $value['wscate_id'];
            $where = "wscate_path like '%," . $id . ",%' or wscate_path like '%," . $id . "'";
            $count = self::where($where)->count();
            if ($count > 0) {
                return false;
            }

            // 删除图片
            if (is_array($value['wscate_image'])) {
                foreach ($value['wscate_image'] as $key => $value) {
                    del_file($value['file_path']);
                }
            }
        });

        // 删除后
        self::afterDelete(function ($value) {
            // 删除缓存
            self::delete_cache($value['wscate_siteid'], $value['wscate_columnid']);
        });
    }

    // 删除缓存
    public static function delete_cache($siteid = 0, $columnid = 0)
    {
        $cache_name = 'wscate_list_' . $siteid . '_' . $columnid;
        if (cache('?' . $cache_name)) {
            cache($cache_name, null);
        }
    }

    // 调用分类
    public static function getList($siteid, $columnid)
    {
        // 有缓存直接调用缓存
        $cache_name = 'wscate_list_' . $siteid . '_' . $columnid;
        if (cache('?' . $cache_name)) {
            return cache($cache_name);
        }

        $where = 'wscate_siteid=' . $siteid . ' and wscate_columnid=' . $columnid;
        $field = 'wscate_id, wscate_name, wscate_pid, wscate_path, wscate_child';
        $list = self::where($where)->order('wscate_sort asc')->column($field, 'wscate_id');

        // 缓存分类
        cache($cache_name, $list);

        return $list;
    }

    public static function getZtree($siteid, $columnid, $cateid = '')
    {
        $cateid = explode(',', $cateid);
        $list = self::getList($siteid, $columnid);
        $data = array();
        foreach ($list as $key => $value) {
            $data[] = [
                'id' => $value['wscate_id'],
                'pId' => $value['wscate_pid'],
                'name' => $value['wscate_name'],
                'path' => $value['wscate_path'],
                'checked' => in_array($value['wscate_id'], $cateid) ? true : false,
            ];
        }
        return $data;
    }

    // 图片进行序列化
    public function setWscateImageAttr($value)
    {
        return serialize($value);
    }

    // 序列化
    public function getWscateImageAttr($value)
    {
        return unserialize($value);
    }

    // 获取器 wscate_cate_html 新添加字段
    public function getWscateHomeHtmlAttr($value, $data)
    {
        $value = $data['wscate_home'];
        $status = [
            0 => '',
            1 => '<i class="icon icon-check text-success" title="首页"></i>',
        ];
        return isset($status[$value]) ? $status[$value] : '';
    }

    // 获取器 wscate_field_html 新添加字段
    public function getWscateRecommendHtmlAttr($value, $data)
    {
        $value = $data['wscate_recommend'];
        $status = [
            0 => '',
            1 => '<i class="icon icon-check" title="推荐"></i>',
        ];
        return isset($status[$value]) ? $status[$value] : '';
    }

    /**
     * [tree_to_data 对 树型tree 数据 进行调整]
     * @param  [type]  $tree  [description]
     * @param  integer $pid   [description]
     * @param  string  $path  [description]
     * @param  array   &$list [description]
     * @return [type]         [description]
     */
    public function tree_to_data($tree, $pid = 0, $path = '0', &$list = array())
    {
        static $sort = 0;
        //dump($tree);
        if (is_array($tree)) {
            foreach ($tree as $key => $item) {
                $sort++;
                $reffer = $item;
                unset($reffer['children']);
                $reffer['wscate_sort'] = $sort;
                $reffer['wscate_pid'] = $pid;
                $reffer['wscate_path'] = $path;
                $reffer['wscate_child'] = 0;
                if (isset($item['children']) and count($item['children']) > 0) {
                    $reffer['wscate_child'] = 1;
                }
                $list[] = $reffer;

                if (isset($item['children'])) {
                    $mypath = $reffer['wscate_path'] . ',' . $reffer['wscate_id'];
                    self::tree_to_data($item['children'], $item['wscate_id'], $mypath, $list);
                }
            }
        }
        return $list;
    }

    /**
     * [tree_to_html 生成html页面]
     * @param  [type]  $tree [description]
     * @param  integer $num  [description]
     * @return [type]        [description]
     */
    public function tree_to_html($tree, $num = 0)
    {
        $html = '';
        $num++;
        foreach ($tree as $item) {
            $html .= '<li class="dd-item" data-wscate_id="' . $item['wscate_id'] . '">';
            $html .= '  <div class="dd-handle">' . $item['wscate_name'] . '</div>';
            if (isset($item['children']) and count($item['children']) > 0) {
                if ($num < 3) {
                    $html .= '<ol class="dd-list">';
                    $html .= self::tree_to_html($item['children'], $num);
                    $html .= '</ol>';
                }
            }
            $html .= '</li>';
        }
        return $html;
    }

    /**
     * [update_sort 更新排序]
     * @param  [type] $siteid   [description]
     * @param  [type] $columnid [description]
     * @return [type]           [description]
     */
    public function update_sort($siteid = 0, $columnid = 0)
    {
        if ($siteid <= 0 || $columnid <= 0) {
            return false;
        }
        // 分类列表
        $list = self::where('wscate_siteid=' . $siteid . ' and wscate_columnid=' . $columnid)
            ->field('wscate_id,wscate_pid,wscate_path')
            ->order('wscate_sort')->select()->toArray();
        $tree = list_to_tree($list, 'wscate_id', 'wscate_pid');

        // 更新排序
        $data = self::tree_to_data($tree);
        self::saveAll($data);

        unset($list, $tree, $data);

        return true;
    }
}
